package com.chinasoft.controller;

import com.alibaba.fastjson.JSONArray;
import com.chinasoft.dao.Impl.TopicDAOImpl;
import com.chinasoft.dao.TopicDAO;
import com.chinasoft.entity.Topic;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by YE on 2018/5/22.
 */
@WebServlet(name = "TopicServlet", urlPatterns = {"/topic"})
public class TopicServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TopicDAO topicDAO = new TopicDAOImpl();
        Topic topic=null;
        String topics=null;
        PrintWriter out = response.getWriter();
        List<Topic> list=null;
        String topicop=request.getParameter("topicop");
        if("getall".equals(topicop)){
            int sid= Integer.parseInt(request.getParameter("sid"));
            if(sid==0){
                list=topicDAO.getTopics();
                topics=JSONArray.toJSONString(list);
            }else{
                list=topicDAO.getTopicsBySid(sid);
                topics=JSONArray.toJSONString(list);
            }
            out.print(topics);
        }if("delete".equals(topicop)){
            int tid=Integer.parseInt(request.getParameter("id"));
            out.print(topicDAO.deleteTopic(tid));
        }if("update".equals(topicop)){
            topic=new Topic();
            topic.setTid(Integer.parseInt(request.getParameter("tid")));
            topic.setSid(Integer.parseInt(request.getParameter("sid")));
            topic.setTname(request.getParameter("tname"));
            out.print(topicDAO.updateTopic(topic));
        }if("insert".equals(topicop)){
            topic=new Topic();
            topic.setSid(Integer.parseInt(request.getParameter("sid")));
            topic.setTname(request.getParameter("tname"));
            out.print(topicDAO.addTopic(topic));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
